//
//  STLauncher.swift
//  StartimesON
//
//  Created by Toj on 2/15/23.
//  Copyright © 2023 Google. All rights reserved.
//

import UIKit
import GoogleMobileAds
import MBProgressHUD
import TTCOM_iOS

enum STLaunchTypes: String {
    case desktop
    case openURL
    case locationPush
    case remotePush
    case other
}

class STLauncher: NSObject {
    
    static let shared = STLauncher()
    override init() {
        super.init()
        registerNotification()
    }
    
    private(set) var launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    
    public func setup(application: UIApplication, didFinishLaunchingWith options: [UIApplication.LaunchOptionsKey: Any]?) {
        launchOptions = options
        
        setupLaunchView()
        
        mainThreadLaunched()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.asyncAfterLaunched()
        }
        
        DispatchQueue.global(qos: .userInitiated).async {
            self.asyncThreadLaunched()
        }
        
        ds_startLaunch()
    }
    
    var launchVC: UIViewController?
}

@objc private extension STLauncher {
    
    func loginSuccess() {
        launchVC?.view.removeFromSuperview()
        launchVC?.removeFromParent()
        launchVC = nil
        print("-->toj: 启动页 退出" + #function)
    }
}

extension STLauncher {
    
    func setupLaunchView() {
        print("-->toj: 启动页 展示 func:" + #function)
        guard let rootVC = UIApplication.shared.delegate?.window??.rootViewController
        else { return }
        
        guard !STUserCenter.default.isLogin else {
            loginSuccess()
            return
        }
        
        let vc = LaunchScreenViewController()
        launchVC = vc
        rootVC.addChild(vc)
        vc.view.frame = UIApplication.shared.keyWindow?.bounds ?? .zero
        rootVC.view.addSubview(vc.view)
    }
}

private extension STLauncher {
    
    func setupSDKs() {
        // SDK广告
        GADMobileAds.sharedInstance().start { _ in }
    }
}

// 必要启动
// 不需要延迟启动项
private extension STLauncher {
    
    func mainThreadLaunched() {
        // UI 初始化
        STUIAppearance.shared.setup()
        [UIView]().forEach { $0.removeFromSuperview() }
        
        // 通知
        STPNotificationCenter.shared.setup()
        
        // 国际化
        CMLocalized.defalut.setup()
        
        setupSDKs()
        // STAdmobManager.manager.launchPreloadCacheAds()
        
        let isJailbroken = STJailbreakTools.shared.isJailbroken
        print(isJailbroken)
        
        IAPRequest.shared.setup()
    }
}

// asyncAfterLaunched
// 非必要项
// 异步延迟2秒钟启动
private extension STLauncher {
    
    func asyncAfterLaunched() {
        
    }
}

// asyncThreadLaunched
// 非必要项
// 异步启动
private extension STLauncher {
    
    func asyncThreadLaunched() {
        STLoginManager.manager.request(autoLogin: { [weak self] in
            self?.presentAppOpenAd()
        })
    }
    
    func presentAppOpenAd() {
        print("-->toj: 读取本地缓存数据 func:" + #function)
        guard let admobModel = STAdManager.manager.appOpenAdmobModelCache() else {
            STAdmobManager.manager.requestAppOpenAd()
            print("-->toj: 本地没有缓存数据 func1:" + #function)
            return
        }
        
        let isPreparedAd = STAdmobManager.manager.isPreparedAd(admobModel: admobModel)
        guard isPreparedAd else {
            print("-->toj: app没有预加载的广告对象 func:" + #function)
            STAdmobManager.manager.requestAppOpenAd()
            return
        }
        
        print("-->toj: 有预加载的广告对象 func:" + #function)
        STAdmobManager.manager.presentAd(admobModel: admobModel)
        DispatchQueue.main.asyncAfter(deadline: .now()+0.05) {
            STAdmobManager.manager.requestAppOpenAd()
        }
    }
}

// asyncThreadLaunched
// 非必要项
// 异步启动
private extension STLauncher {
    
    func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: .loginSuccessNotification, object: nil)
    }
}

private extension STLauncher {
    
    func ds_startLaunch() {
        var extention = [String: Any]()
        /// 正常启动
        var launchType = STLaunchTypes.desktop
        // ios 10之前，app杀死状态下，点击推送，进入app，取localNotification 获取推送消息
        // ios 10以后已经不建议使用了，但是依然可以用
        if launchOptions != nil {
            launchType = .other
            
            /// openURL启动
            if let url = launchOptions?[UIApplication.LaunchOptionsKey.url] as? URL {
                let absoluteString = url.absoluteString
                if !absoluteString.isEmpty {
                    extention["url"] = absoluteString
                }
                launchType = .openURL
            }
            
            /// locationPush启动
            if let local = launchOptions?[.localNotification] as? UILocalNotification {
                let userInfo = local.userInfo ?? [:]
                extention["msgeid"] = userInfo[UPPushKey.firebaseMessageID.rawValue]
                launchType = .locationPush
            }
            
            /// remotePush启动
            if let notification = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] {
                print("-->toj: notification:\(notification)")
                launchType = .remotePush
            }
        }
        
        extention["launchType"] = launchType.rawValue
        // 埋点
        let category = "launch"
        let action = "start"
        print("-->toj: category: \(category), action:\(action), extension: \(extention)")
        guard let options = launchOptions else { return }
        
        let appDelegate = UIApplication.shared.delegate as? AppDelegate
        let window = appDelegate?.window
        window?.makeToast("\(options)", duration: 3, position: CSToastPositionCenter)
        window?.makeToast("\(extention)", duration: 3, position: CSToastPositionCenter)
    }
}
